﻿#region Version Info
/* ========================================================================
* 【本类功能概述】
* 
* 作者：李荣楠
* 时间：2013-11-27 17:50:50
* 文件名：BaseEntity
* .net版本：4.0 
* ========================================================================
*/
#endregion
using System.Reflection;
using System;
using System.Data;

namespace LCL.Entity
{
    public class BaseEntity
    {
        private string tableName = "Table";

        public string TableName
        {
            get { return tableName; }
            set { tableName = value; }
        }
        /// <summary>
        /// 获取当前实体对象的Insert语句
        /// </summary>
        /// <returns></returns>
        public string GetInsertStr()
        {
            Type t = this.GetType();
            string tab = "";
            string feilds = "";
            string values = "";
            string str = "";
            try
            {
                PropertyInfo[] propertys = t.GetProperties();
                foreach (PropertyInfo prop in propertys)
                {
                    if (prop.Name == "TableName")
                    {
                        tab = prop.GetValue(this, null).ToString();
                    }
                    else
                    {
                        feilds += prop.Name + ",";
                        BaseEntityFeild bef=(BaseEntityFeild)prop.GetValue(this, null);
                        if (bef.Type == FieldType.Primary) continue;
                        if (bef.Data == null) throw new Exception("数据不能为NULL");
                        if (bef.DataType == SqlDbType.NVarChar||
                            bef.DataType == SqlDbType.NChar||
                            bef.DataType == SqlDbType.Text||
                            bef.DataType == SqlDbType.NChar)
                        {
                            values += "'" + bef.Data + "',";
                        }
                        else
                        {
                            values += bef.Data + ",";

                        }
                    }

                }
                values = values.TrimEnd(',');
                feilds = feilds.TrimEnd(',');
                str = string.Format("insert into {0} ({1}) values ({2})", tab, feilds, values);
            }
            catch (Exception)
            {

                throw;
            }
            return str;
        }
    }
}
